package com.shoy.myapp.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.util.Log;

import java.util.Stack;

/**
 * 引用程序Activity管理类
 *
 * @author shoy
 * @created 2015/4/1
 */
public class AppManager {
    private static Stack<Activity> activityStack;
    private static AppManager instance;

    private AppManager() {
        activityStack = new Stack<Activity>();
    }

    /**
     * 单一实例
     */
    public static AppManager getInstance() {
        if (instance == null) {
            instance = new AppManager();
        }
        return instance;
    }

    /**
     * 添加Activity
     */
    public void add(Activity activity) {
        activityStack.add(activity);
    }

    /**
     * 当前Activity
     *
     * @return Activity
     */
    public Activity current() {
        return activityStack.lastElement();
    }

    public AppContext getApp() {
        return (AppContext) current().getApplicationContext();
    }

    /**
     * 关闭当前Activity
     */
    public void finish() {
        finish(current());
    }

    /**
     * 关闭指定Activity
     */
    public void finish(Activity activity) {
        if (null == activity)
            return;
        activityStack.remove(activity);
        activity.finish();
    }

    /**
     * 关闭一类Activity
     *
     * @param cls 类
     */
    public void finish(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls))
                finish(activity);
        }
    }

    /**
     * 关闭所有
     */
    public void finishAll() {
        for (Activity anActivityStack : activityStack) {
            if (null != anActivityStack) {
                anActivityStack.finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public void exit(Context context) {
        try {
            finishAll();
            ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.restartPackage(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
            Log.e(Constants.TAG, e.getMessage(), e);
        }
    }
}
